<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="decorator" content="default"/>
    <title>报表查看</title>
    <link rel="stylesheet" href="/css/font-awesome.min.6.4.css">
    <link rel="stylesheet" href="/css/main.css">
    <link th:href="@{/css/pm/statistics.css}" rel="stylesheet">
</head>
<body>
    <div class="report-container">
        <!-- 页面标题和操作按钮 -->
        <div class="report-header">
            <h1 class="report-title">
                <i class="fa fa-file-text"></i> 报表查看
            </h1>
            <div class="report-actions">
                <button type="button" class="btn btn-primary" onclick="exportCurrentReport()">
                    <i class="fa fa-download"></i> 导出当前报表
                </button>
                <button type="button" class="btn btn-secondary" onclick="goBack()">
                    <i class="fa fa-arrow-left"></i> 返回统计
                </button>
            </div>
        </div>
        
        <!-- 筛选条件区域 -->
        <div class="report-filter-section">
            <div class="filter-row">
                <div class="filter-group">
                    <div class="filter-label">报表类型</div>
                    <select id="reportType" class="form-control" onchange="loadReportData()">
                        <option value="PROJECT_BASIC_INFO">项目基本信息报表</option>
                        <option value="PROJECT_STATISTICS">项目统计报表</option>
                        <option value="ISSUE_DETAIL_REPORT">需求明细报表</option>
                        <option value="CUSTOMER_PROJECT_REPORT">客户项目关系报表</option>
                        <option value="COMPREHENSIVE_REPORT">综合项目分析报表</option>
                    </select>
                </div>
                <div class="filter-group">
                    <div class="filter-label">开始时间</div>
                    <input type="date" id="startDate" class="form-control" onchange="loadReportData()" />
                </div>
                <div class="filter-group">
                    <div class="filter-label">结束时间</div>
                    <input type="date" id="endDate" class="form-control" onchange="loadReportData()" />
                </div>
                <div class="filter-group">
                    <button type="button" class="btn btn-info" onclick="loadReportData()">
                        <i class="fa fa-refresh"></i> 刷新数据
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 数据汇总信息 -->
        <div id="dataSummary" class="data-summary" style="display: none;">
            <div class="summary-item">
                <span>数据总数：</span>
                <span class="summary-value" id="totalCount">0</span>
            </div>
            <div class="summary-item">
                <span>筛选时间：</span>
                <span class="summary-value" id="dateRange">-</span>
            </div>
            <div class="summary-item">
                <span>报表类型：</span>
                <span class="summary-value" id="reportTypeName">-</span>
            </div>
        </div>
        
        <!-- 报表内容区域 -->
        <div class="report-content">
            <div id="loadingOverlay" class="loading-overlay" style="display: none;">
                <div style="text-align: center;">
                    <div class="loading-spinner"></div>
                    <p style="margin-top: 10px; color: #666;">正在加载数据...</p>
                </div>
            </div>
            
            <div id="noData" class="no-data" style="display: none;">
                <i class="fa fa-inbox"></i>
                <h4>暂无数据</h4>
                <p>请选择筛选条件后查看报表数据</p>
            </div>
            
            <div id="dataTableContainer" class="data-table-container" style="display: none;">
                <table id="dataTable" class="data-table">
                    <thead id="tableHeader">
                        <!-- 表头将通过JavaScript动态生成 -->
                    </thead>
                    <tbody id="tableBody">
                        <!-- 表格数据将通过JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>
            
            <!-- 分页控件 -->
            <div id="paginationContainer" class="pagination-container" style="display: none;">
                <div class="pagination-info">
                    显示第 <span id="startRow">0</span> - <span id="endRow">0</span> 条，共 <span id="totalRows">0</span> 条数据
                </div>
                <div class="pagination-controls">
                    <button class="pagination-btn" onclick="changePage(-1)" id="prevBtn" disabled>
                        <i class="fa fa-chevron-left"></i> 上一页
                    </button>
                    <span id="pageInfo" style="padding: 6px 12px;">第 0 页</span>
                    <button class="pagination-btn" onclick="changePage(1)" id="nextBtn" disabled>
                        下一页 <i class="fa fa-chevron-right"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>

	<th:block th:include="include :: footer" />
    <script type="text/javascript">
        // 全局变量
        let currentPage = 1;
        let pageSize = 20;
        let totalRows = 0;
        let currentData = [];
        
        $(document).ready(function() {
            // 设置默认日期范围（最近30天）
            setDefaultDateRange();
            
            // 页面加载时自动加载数据
            setTimeout(function() {
                loadReportData();
            }, 500);
        });
        
        // 设置默认日期范围
        function setDefaultDateRange() {
            var endDate = new Date();
            var startDate = new Date();
            startDate.setDate(startDate.getDate() - 30);
            
            $('#startDate').val(formatDate(startDate));
            $('#endDate').val(formatDate(endDate));
        }
        
        // 格式化日期为YYYY-MM-DD
        function formatDate(date) {
            var year = date.getFullYear();
            var month = String(date.getMonth() + 1).padStart(2, '0');
            var day = String(date.getDate()).padStart(2, '0');
            return year + '-' + month + '-' + day;
        }
        
        // 加载报表数据
        function loadReportData() {
            var startDate = $('#startDate').val();
            var endDate = $('#endDate').val();
            var reportType = $('#reportType').val();
            
            if (!startDate || !endDate) {
                $.modal.alert('请选择开始时间和结束时间');
                return;
            }
            
            if (new Date(startDate) > new Date(endDate)) {
                $.modal.alert('开始时间不能晚于结束时间');
                return;
            }
            
            // 显示加载动画
            showLoading(true);
            
            $.ajax({
                url: ctx + "statistics/report/preview",
                type: "get",
                data: {
                    startDate: startDate,
                    endDate: endDate,
                    reportType: reportType
                },
                success: function(result) {
                    showLoading(false);
                    if (result.code == 0) {
                        currentData = result.data || [];
                        totalRows = currentData.length;
                        currentPage = 1;
                        
                        updateDataSummary();
                        renderDataTable();
                        updatePagination();
                    } else {
                        $.modal.alert(result.msg || '获取数据失败');
                        showNoData();
                    }
                },
                error: function() {
                    showLoading(false);
                    $.modal.alert('获取数据失败，请检查网络连接');
                    showNoData();
                }
            });
        }
        
        // 显示/隐藏加载动画
        function showLoading(show) {
            if (show) {
                $('#loadingOverlay').show();
                $('#dataTableContainer').hide();
                $('#paginationContainer').hide();
                $('#dataSummary').hide();
                $('#noData').hide();
            } else {
                $('#loadingOverlay').hide();
            }
        }
        
        // 显示无数据状态
        function showNoData() {
            $('#dataTableContainer').hide();
            $('#paginationContainer').hide();
            $('#dataSummary').hide();
            $('#noData').show();
        }
        
        // 更新数据汇总信息
        function updateDataSummary() {
            $('#totalCount').text(totalRows);
            $('#dateRange').text($('#startDate').val() + ' 至 ' + $('#endDate').val());
            $('#reportTypeName').text($('#reportType option:selected').text());
            $('#dataSummary').show();
        }
        
        // 渲染数据表格
        function renderDataTable() {
            if (currentData.length === 0) {
                showNoData();
                return;
            }
            
            // 计算当前页的数据
            var startIndex = (currentPage - 1) * pageSize;
            var endIndex = Math.min(startIndex + pageSize, totalRows);
            var pageData = currentData.slice(startIndex, endIndex);
            
            // 获取表头
            var headers = Object.keys(currentData[0]);
            
            // 渲染表头
            var headerHtml = '<tr>';
            headers.forEach(function(header) {
                headerHtml += '<th>' + header + '</th>';
            });
            headerHtml += '</tr>';
            $('#tableHeader').html(headerHtml);
            
            // 渲染表格数据
            var bodyHtml = '';
            pageData.forEach(function(row) {
                bodyHtml += '<tr>';
                headers.forEach(function(header) {
                    var value = row[header] || '';
                    // 处理过长的文本
                    if (String(value).length > 100) {
                        value = String(value).substring(0, 100) + '...';
                    }
                    bodyHtml += '<td title="' + value + '">' + value + '</td>';
                });
                bodyHtml += '</tr>';
            });
            $('#tableBody').html(bodyHtml);
            
            $('#dataTableContainer').show();
            $('#paginationContainer').show();
            $('#noData').hide();
        }
        
        // 更新分页信息
        function updatePagination() {
            var totalPages = Math.ceil(totalRows / pageSize);
            var startRow = (currentPage - 1) * pageSize + 1;
            var endRow = Math.min(currentPage * pageSize, totalRows);
            
            $('#startRow').text(startRow);
            $('#endRow').text(endRow);
            $('#totalRows').text(totalRows);
            $('#pageInfo').text('第 ' + currentPage + ' 页 / 共 ' + totalPages + ' 页');
            
            // 更新按钮状态
            $('#prevBtn').prop('disabled', currentPage <= 1);
            $('#nextBtn').prop('disabled', currentPage >= totalPages);
        }
        
        // 切换页面
        function changePage(delta) {
            var newPage = currentPage + delta;
            var totalPages = Math.ceil(totalRows / pageSize);
            
            if (newPage < 1 || newPage > totalPages) {
                return;
            }
            
            currentPage = newPage;
            renderDataTable();
            updatePagination();
            
            // 滚动到表格顶部
            $('html, body').animate({
                scrollTop: $('#dataTableContainer').offset().top - 100
            }, 300);
        }
        
        // 导出当前报表
        function exportCurrentReport() {
            var startDate = $('#startDate').val();
            var endDate = $('#endDate').val();
            var reportType = $('#reportType').val();
            var format = 'EXCEL'; // 固定为Excel格式
            
            if (!startDate || !endDate) {
                $.modal.alert('请选择开始时间和结束时间');
                return;
            }
            
            if (new Date(startDate) > new Date(endDate)) {
                $.modal.alert('开始时间不能晚于结束时间');
                return;
            }
            
            if (currentData.length === 0) {
                $.modal.alert('当前没有数据可导出');
                return;
            }
            
            $.modal.loading("正在生成报表，请稍候...");
            
            // 创建表单进行提交
            var form = $('<form>', {
                method: 'post',
                action: ctx + 'statistics/report/export'
            });
            
            $('<input>').attr({
                type: 'hidden',
                name: 'startDate',
                value: startDate
            }).appendTo(form);
            
            $('<input>').attr({
                type: 'hidden',
                name: 'endDate',
                value: endDate
            }).appendTo(form);
            
            $('<input>').attr({
                type: 'hidden',
                name: 'reportType',
                value: reportType
            }).appendTo(form);
            
            $('<input>').attr({
                type: 'hidden',
                name: 'format',
                value: format
            }).appendTo(form);
            
            form.appendTo('body').submit().remove();
            
            // 3秒后关闭加载提示
            setTimeout(function() {
                $.modal.closeLoading();
                $.modal.msgSuccess('报表导出成功！');
            }, 3000);
        }
        
        // 返回统计页面
        function goBack() {
            window.location.href = ctx + 'statistics/index';
        }
        
        // 键盘快捷键支持
        $(document).keydown(function(e) {
            // Ctrl+R 刷新数据
            if (e.ctrlKey && e.keyCode === 82) {
                e.preventDefault();
                loadReportData();
            }
            
            // 左右箭头切换页面
            if (e.keyCode === 37) { // 左箭头
                changePage(-1);
            } else if (e.keyCode === 39) { // 右箭头
                changePage(1);
            }
        });
    </script>
</body>
</html>